#include "../../muduo/channel.hpp"
#include "../../muduo/socket.hpp"
#include "../../muduo/log.hpp"
#include "../../muduo/connection.hpp"

std::unordered_map<uint64_t,Muduo::Connection::PtrConnection> _conns;
uint64_t conn_id = 0;
void ConnectionDestroy(const Muduo::Connection::PtrConnection&conn)
{
    _conns.erase(conn->Id());
}

void OnConnected(const Muduo::Connection::PtrConnection&conn)
{
    DLOG("new connection:%p",conn.get());
}


void OnMessage(const Muduo::Connection::PtrConnection& conn,Muduo::Buffer * buf)
{
    DLOG("%s",buf->ReadPosition());
    buf->MoveReadOffset(buf->ReadAbleSize());
    std::string str = "hello" "world";
    conn->Send(str.c_str(),str.size());
    // conn->Shutdown();
}



void Accepter(Muduo::EventLoop * loop,Muduo::Channel * lst_channel)
{
    int fd = lst_channel->Fd();
    int newfd = accept(fd,nullptr,nullptr);
    if(newfd<0) return;
    conn_id++;
    Muduo::Connection::PtrConnection conn(new Muduo::Connection(loop,conn_id,newfd));
    conn->SetMessageCallback(std::bind(OnMessage,std::placeholders::_1,std::placeholders::_2));
    conn->SetSrvClosedCallback(std::bind(ConnectionDestroy,std::placeholders::_1));
    conn->SetConnectedCallback(std::bind(OnConnected,std::placeholders::_1));
    conn->EnableInactiveRelease(10);
    conn->Established();//就绪初始化
    _conns.insert(std::make_pair(conn_id,conn));
}

int main()
{
    srand(time(nullptr));
    Muduo::EventLoop loop;
    Muduo::Socket lst_sock;
    lst_sock.CreateServer(8080);
    Muduo::Channel channel(&loop,lst_sock.Fd());
    channel.SetReadCallback(std::bind(Accepter,&loop,&channel));
    channel.EnableRead();
    while(true)
    {
        loop.Start();
    }
    lst_sock.Close();
    return 0;
}
